package com.example.d8_tcp5;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * TCP 实现 HTTP
 */
public class Server {
    public static void main(String[] args) throws IOException {

        System.out.println("服务端启动...");

        ServerSocket serverSocket = new ServerSocket(8888);

        while (true) {
            Socket socket = serverSocket.accept();
            System.out.println("客户端连接成功");
            System.out.println(socket.getRemoteSocketAddress());
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        OutputStream outputStream = socket.getOutputStream();
                        PrintStream printStream = new PrintStream(outputStream);
                        String content = "<html><body><div style='color:red'>客户端你好！我是小智！</div></body></html>";
                        printStream.println("HTTP/1.1 200 OK");
                        printStream.println("Content-Type: text/html; charset=utf-8");
                        printStream.println("Content-Length: " + content.getBytes().length);
                        printStream.println(content);
                        printStream.flush();
                        socket.close();
                    } catch (Exception e) {
                        System.out.println("有妖气！");
                    }
                }
            }).start();
        }

    }
}
